package com.atguigu.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.Utils;
import com.google.code.kaptcha.Constants;
import com.google.gson.Gson;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    UserService userService = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	/*protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String hide = request.getParameter("hide");
		if("login".equals(hide)) {
			login(request,response);
		}else if("regist".equals(hide)){
			regist(request,response);
		}
	}*/
    /*//优化一：采用了反射
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    	String action = request.getParameter("hide");
    	try {
			Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(this, request,response);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }*/
    
	protected void login(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
//		String username = request.getParameter("username");
//		String password = request.getParameter("password");
		User user = Utils.copyParamToBean(request.getParameterMap(), new User());
		User login = userService.login(new User(0, user.getUsername(), user.getPassword(), null));
		if(login != null) {
			//System.out.println("登录成功!");
			request.getSession().setAttribute("user", login);
			request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response);
		}else {
			//System.out.println("登录失败！");
			request.setAttribute("msg", "登录失败，用户名或密码错误！");
			request.setAttribute("name", user.getUsername());
			request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
			
		}
	}
	
	protected void regist(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String token = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		request.getSession().removeAttribute(token);
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		
		//验证码
		if(token != null && token.equalsIgnoreCase(code)) {
			if(userService.existUsername(username)) {
				//System.out.println("用户已经存在，注册失败！");
				request.setAttribute("msg", "用户已经存在，注册失败！");
				request.setAttribute("name", username);
				request.setAttribute("email", email);
				request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
			}else {
				userService.regist(new User(0, username, password, email));
				//System.out.println("注册成功！");
				request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
			}
		}else {
			request.setAttribute("msg", "验证码错误，注册失败！");
			request.setAttribute("name", username);
			request.setAttribute("email", email);
			request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
		}
	}
	
	protected void logout(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.getSession().removeAttribute("user");
		//request.getSession().invalidate();
		response.sendRedirect(request.getContextPath());
	}
	
	protected void ajaxRegist(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String username = request.getParameter("username");
		boolean existUsername = userService.existUsername(username);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("existUsername",existUsername);
		Gson gson = new Gson();
		String json = gson.toJson(map);
		response.getWriter().write(json);
	}

}
